package itrans;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.*;

public class GetStop extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		process(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		process(request, response);
	}
	
	/* Takes the current session's user and generates a list of
	 * stops based on user ID, and then returns a list of
	 * stop beans to the client
	 */
	public void process(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		HttpSession session = request.getSession(true);
		UserBean userBean = (UserBean) session.getAttribute(PublicConstants.USERBEAN_ATTR);
		List<StopBean> stopBeans = getStops(userBean);
		session.setAttribute("stopBeans", stopBeans);
		request.getRequestDispatcher("/WEB-INF/show_saved_stops.jsp").forward(request, response);
	}
	
	private List<StopBean> getStops(UserBean userBean)
	{
		Connection con;
		List<StopBean> stopBeanList = new ArrayList<StopBean>();
		
		String searchQuery = "SELECT * FROM MyStops where user_id = ?";

		try {
		  DataSource dbcp = (DataSource)getServletContext().getAttribute("dbpool");
		  con = dbcp.getConnection();
		  
		  PreparedStatement query = con.prepareStatement(searchQuery);
		  query.setInt(1, userBean.getId());
		  
		  ResultSet rs = query.executeQuery();
		  // Create a list of stop beans from the results
		  while (rs.next()) {
			StopBean sb = new StopBean();
			sb.setStopId(rs.getString("stopid"));
			sb.setRunId(rs.getString("runid"));
			sb.setRouteId(rs.getString("routeid"));
			sb.setStopTitle(rs.getString("stop_title"));
			sb.setUserId(rs.getInt("user_id"));
			stopBeanList.add(sb);
		  }

		  rs.close();
		  query.close();
		  con.close();
		}
		catch(SQLException ex) {
			System.out.println("SQLException: " + ex.getMessage());
		}
		catch (Exception e) {
		  e.printStackTrace();
		}
		
		return stopBeanList;
	}
}
